<?php
    ob_start();
    session_start();
    include("dbinfo.inc.php");
    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die("Unable to select database");

    // get userID from the DB using the name
    $query="select ID from Account where userName like '$_POST[userName]';";
    $resultID=mysql_query($query);
    if (!$resultID) {
        //echo "Error selecting ID from Account: " . mysql_error();
        //die("");
        $userExists=0;
    }
    else {
        $userExists=1;
        $userID=mysql_result($resultID,0, "ID");
    }
    
    $query = "SELECT * FROM TrailHead WHERE";
    $insert_params = "INSERT INTO Filter (userID,";
    $insert_values = "VALUES ($userID,";
    
    //Starting altitude filter
    if((int)$_POST[altitude] >= 0 && (int)$_POST[altitude] < 9000){
        $upper = $_POST[altitude]+3000;
        $query.=" start_altitude <=$upper AND start_altitude >=$_POST[altitude]";
        $addAnd=1;
        $_SESSION['altitude'] = $_POST[altitude];

	$mid_start_alt = $_POST[altitude] + 1500;
	$insert_params.="start_altitude";
	$insert_values.="$mid_start_alt";
    }
    elseif((int)$_POST[altitude] == 9000){
        $query.=" start_altitude >=$_POST[altitude]";
        $addAnd=1;
        $_SESSION['altitude'] = $_POST[altitude];

	$insert_params.="start_altitude";
	$insert_values.="$_POST[altitude]";
    }else{
        $addAnd=0;
        $_SESSION['altitude'] = NULL;
    }
    
    //Dogs allowed filter
    if((int)$_POST[dogs] != -1){
        if ($addAnd==1) {
            $query.=" AND";
	    $insert_params.=",";
	    $insert_values.=",";
        }
        $addAnd=1;
        $query.=" dog like '$_POST[dogs]'";
        $_SESSION['dogs'] = $_POST[dogs];

	$insert_params.="dog";
	$insert_values.="'$_POST[dogs]'";
    }else{
        $addAnd=0;
        $_SESSION['dogs'] = NULL;
    }
    
    //Bikes allowed filter
    if((int)$_POST[bikes] != -1){
        if ($addAnd==1) {
            $query.=" AND";
	    $insert_params.=",";
	    $insert_values.=",";
        }
        $query.=" bike like '$_POST[bikes]'";
        $_SESSION['bikes'] = $_POST[bikes];

	$insert_params.="bike";
	$insert_values.="'$_POST[bikes]'";
    }else{
        $_SESSION['bikes'] = NULL;
    }
    
    if(strstr($query, '<=') != FALSE || strstr($query, '>=') != FALSE || strstr($query, 'like') != FALSE){
        $_SESSION['filterTrailHeadQuery'] = $query;
    }else{
        $_SESSION['filterTrailHeadQuery'] = NULL;
        $_SESSION['altitude'] = NULL;
        $_SESSION['dogs'] = NULL;
        $_SESSION['bikes'] = NULL;
    }

    $query.=";";
    $insert_params.=") ";
    $insert_values.=");";
    if ($userExists == 1 and $insert_values != "VALUES ($userID,);") {
	$insert_query=$insert_params . $insert_values;
	if (!mysql_query($insert_query)) {
	    echo "Error saving filter: " . mysql_error();
	}
    }
    
    mysql_close();
    session_write_close();
    header("Location: index.php");
    ob_flush();
    ?>
